package com.lz.linklist;

/**
 * 双向链表
 */
public class LinkList<T> {
    private Node<T> head;
    private Node<T> tail;
    private int size;

    public Node<T> getHead() {
        return head;
    }

    public void setHead(Node<T> head) {
        this.head = head;
    }

    public Node<T> getTail() {
        return tail;
    }

    public void setTail(Node<T> tail) {
        this.tail = tail;
    }

    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }

    public LinkList() {
        head = null;
        tail = null;
        size = 0;
    }
    public void add(T data) {
        Node node = new Node(data);
        if (head == null) {
            head = node;
            tail = node;
            size++;
        } else {
            tail.next = node;
            node.pre = tail;
            tail = node;
            size++;
        }
    }

    public void del(T data) {
        Node node = head;
        while (node != null) {
            if (node.data == data) {
                node.pre.next = node.next;
                node.next.pre = node.pre;
                size--;
            } else {
                node = node.next;
            }
        }
    }

    public void printAll() {
        Node node = head;
        while (node != null) {
            System.out.print(node.data+",");
            node = node.next;
        }
        System.out.println("---"+size);
    }

    public Node<T> find(T data) {
        Node<T> node = head;
        while (node != null) {
            if (node.data == data) {
                return node;
            } else {
                node = node.next;
            }
        }
        return null;
    }

    /**
     * 查找中间节点
     * @return
     */
    public Node<T> findMiddle() {
        Node<T> slow = head;
        Node<T> fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }

    public static void main(String[] args) {
        LinkList<Integer> linkList = new LinkList<>();
        linkList.add(1);
        linkList.add(4);
        linkList.add(9);
        linkList.add(5);
        linkList.add(8);
        linkList.add(6);
        linkList.add(7);
        linkList.add(2);

        linkList.printAll();
        System.out.println("===========find==========");
        Node<Integer> node = linkList.find(9);
        System.out.println(node.data);
        System.out.println(node.pre.data);
        System.out.println(node.next.data);

        System.out.println("==========middle===========");
        Node<Integer> middle = linkList.findMiddle();
        System.out.println(middle.data);
    }
}
